package cn.kgc.tangcco.utils.aliyun.oss;

import cn.hutool.setting.dialect.Props;
import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.PutObjectResult;
import java.io.*;
import java.net.URL;
import java.util.Date;

/**
 * @author 李昊哲
 * @Description
 * @create 2020/11/6 9:19
 */
public class BaseAliOSSUtil {
    private static ThreadLocal<OSS> t = new ThreadLocal<OSS>();
    private static Props props = new Props("alioss.properties");
    // Endpoint 其它Region请按实际情况填写。
    private static String endpoint = props.getProperty("endpoint");
    // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
    private static String accessKeyId = props.getProperty("accessKeyId");
    private static String accessKeySecret = props.getProperty("accessKeySecret");
    private static String bucketName = props.getProperty("bucketName");

    public static OSS getCliet() {
        if (t.get() != null) {
            return t.get();
        }
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        t.set(ossClient);
        return ossClient;
    }

    public static void close() {
        getCliet().shutdown();
    }

    public static URL upload(InputStream inputStream, String objectName){
        OSS cliet = getCliet();
        // return cliet.putObject(bucketName, objectName, new ByteArrayInputStream(multipartFile.getBytes()));
        cliet.putObject(bucketName,objectName,inputStream);
        GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET);
        // 指定签名URL过期时间为10分钟。
        Date expiration = new Date(System.currentTimeMillis() + 1000 * 60 * 10 );
        req.setExpiration(expiration);
        URL signedUrl = cliet.generatePresignedUrl(req);
        return signedUrl;
    }
}
